package com.itwenke.springbootdemo.shirowebbootjwt.filter;

import com.itwenke.springbootdemo.shirowebbootjwt.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;


import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class JwtAuthorizationFilter extends AuthorizationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(JwtUtil.HEADER);
        if (token == null) {
            return true;
        }

        Claims claims = JwtUtil.getClaimsByToken(token);
        if (!JwtUtil.isTokenExpired(claims.getExpiration())) {
            return true;
        }

        return false;
    }
}
